package com.chenssy.register.core;

import lombok.SneakyThrows;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

/**
 * 心跳计数器
 * @author:chenssy
 * @date:2021/7/14
 */
public class HearbeatMessureRate {

    private HearbeatMessureRate(){
        UpdateLastMinuteTimestampThread updateLastMinuteTimestampThread = new UpdateLastMinuteTimestampThread();
        updateLastMinuteTimestampThread.start();
    }

    private static class HearbeatMessureRateHolder {
        private static HearbeatMessureRate instance = new HearbeatMessureRate();
    }

    public static HearbeatMessureRate getInstance() {
        return HearbeatMessureRateHolder.instance;
    }

    /**
     * 最近一分钟的心跳次数
     */
    private LongAdder lastMinuteHearbeatRate = new LongAdder();

    private Long lastMinuteTimestamp = System.currentTimeMillis();

    /**
     * 增加心跳次数
     */
    public void increment() {
        // 心跳 + 1
        lastMinuteHearbeatRate.increment();
    }

    /**
     * 获取最近一分钟的心跳次数
     * @return
     */
    public Long getLastMinuteHearbeatRate() {
        return this.lastMinuteHearbeatRate.longValue();
    }

    private class UpdateLastMinuteTimestampThread extends Thread {
        @SneakyThrows
        @Override
        public void run() {
            while(true) {
                long currentTimestamp = System.currentTimeMillis();
                if (currentTimestamp - lastMinuteTimestamp > 60 * 1000) {
                    lastMinuteHearbeatRate.reset();
                    lastMinuteTimestamp = System.currentTimeMillis();
                }

                Thread.sleep(1000);
            }
        }
    }
}
